package gloader

import (
	"encoding/json"
	"reflect"
	"wzgames/internal/model/gamep"
	"wzgames/internal/model/mcomm"
	"wzgames/internal/response"
	"wzgames/pkg/utils/stringutil"
)

// 币种方案校验

func CheckGameCurrencyLimit(data []byte, curr string, gameId int32, valType mcomm.ValueType) int16 {
	var err error
	if valType == mcomm.ValueType_Float64Type {
		item := &gamep.GameCurrencyLimit{}
		err = json.Unmarshal(data, item)
		if err != nil {
			//logger.Error("err == ", zap.String("error", err.Error()))
			return response.ErrInternal
		}
		return checkStruct(reflect.TypeOf(item), reflect.ValueOf(item), curr, gameId)
	}

	itemStr := &gamep.GameCurrencyLimitStr{}
	err = json.Unmarshal(data, itemStr)
	if err != nil {
		//logger.Error("err == ", zap.String("error", err.Error()))
		return response.ErrInternal
	}

	return checkStruct(reflect.TypeOf(itemStr), reflect.ValueOf(itemStr), curr, gameId)
}

func checkStruct(refType reflect.Type, refVal reflect.Value, curr string, gameId int32) int16 {
	t := refType.Elem()
	v := refVal.Elem()
	for i := 0; i < v.NumField(); i++ {
		if !t.Field(i).IsExported() {
			continue
		}
		fieldName := t.Field(i).Name
		if gameId != 100 && (fieldName == "AutoCashOutMin" || fieldName == "AutoCashOutMax" || fieldName == "AutoCashOutDefault") {
			continue
		}
		field := v.Field(i)
		switch field.Kind().String() {
		case "float64":
			if !CommMgr().CheckAmountPointByCurrency(curr, stringutil.ToString(field.Interface())) {
				return response.ErrAmount
			}
		case "[]float64":
			arr, ok := field.Interface().([]float64)
			if !ok {
				return response.ErrAmount
			}
			for _, av := range arr {
				if !CommMgr().CheckAmountPointByCurrency(curr, stringutil.ToString(av)) {
					return response.ErrAmount
				}
			}
		case "string":
			if !CommMgr().CheckAmountPointByCurrency(curr, stringutil.ToString(field.Interface())) {
				return response.ErrAmount
			}
		case "[]string":
			arr, ok := field.Interface().([]string)
			if !ok {
				return response.ErrAmount
			}
			for _, av := range arr {
				if !CommMgr().CheckAmountPointByCurrency(curr, av) {
					return response.ErrAmount
				}
			}
		}
	}

	return 0
}
